#!/usr/local/bin/bash

# Export our variables
LIVEFS="/"
FSMNT="/mnt"

# Clean up any previous runs
umount -f ${FSMNT}/dev >/dev/null 2>/dev/null || true
zpool list -H | awk -F '\t' '{print $1;}' | xargs -I % zpool export -f % >/dev/null 2>/dev/null || true

# Install contents of read only uzip to destination pool
bsdinstall hostname
bsdinstall zfsboot
if [ ! -d "/mnt/usr" ] ; then
  exit 1
fi
chflags -R nodump /usr/home/liveuser
chflags -R nodump /var/run/user/1000
su -m root -c 'cd /mnt && dump -0af - /dev/md1.uzip | restore -rf -'
su -m root -c 'cd /mnt && dump -L0af - /dev/md2 | restore -Dyrf -'
bsdinstall config
cat /etc/rc.conf | xargs sysrc -f /mnt/etc/rc.conf
bsdinstall entropy

# Cleanup LiveCD restore specific conents from destination pool
chroot ${FSMNT} rm restoresymtable
chroot ${FSMNT} cp /usr/local/etc/lightdm/lightdm.conf.sample /usr/local/etc/lightdm/lightdm.conf || true
chroot ${FSMNT} cp /usr/local/etc/sddm.conf.sample /usr/local/etc/sddm.conf || true
chroot ${FSMNT} rm /usr/local/etc/gdm/custom.conf || true
chroot ${FSMNT} rm /usr/local/etc/doas.conf
chroot ${FSMNT} rm /etc/rc.conf.local
chroot ${FSMNT} pw userdel liveuser
chroot ${FSMNT} pw groupdel liveuser
chroot ${FSMNT} rm -rf /usr/home/liveuser

# Configure the new installation
mount -t devfs devfs ${FSMNT}/dev
bsdinstall rootpass
dialog --title "Warning" --msgbox 'Please invite at least one user to wheel group!' 5 51
bsdinstall adduser
bsdinstall time

# Enable additional services needed for desktop
chroot ${FSMNT} sysrc linux_enable="YES"
chroot ${FSMNT} sysrc dbus_enable="YES"
chroot ${FSMNT} sysrc dsbdriverd_enable="YES"
if [ -f "/usr/local/sbin/lightdm" ] ; then
  chroot ${FSMNT} sysrc lightdm_enable="YES"
fi
if [ -f "/usr/local/sbin/gdm" ] ; then
  chroot ${FSMNT} sysrc gdm_enable="YES"
fi
if [ -f "/usr/local/bin/sddm" ] ; then
  chroot ${FSMNT} sysrc sddm_enable="YES"
fi

# Cleanup and reboot
echo "Installation finished!"
read -p "Press any key to reboot... " -n1 -s
umount -f ${FSMNT}/dev >/dev/null 2>/dev/null || true
zpool list -H | awk -F '\t' '{print $1;}' | xargs -I % zpool export -f % >/dev/null 2>/dev/null || true
shutdown -r now
